from selenium.webdriver.chrome.webdriver import WebDriver
from time import sleep
from logging import Logger


class WindowAction:
    '''窗口操作
    '''

    def __init__(self, driver: WebDriver, logger: Logger):
        self.driver = driver
        self.logger = logger

    def switch_to_window(self, window_name: str):
        self.driver.switch_to.window(window_name)

    def switch_expand_window(self, index=-1):
        '''切换到新窗口

        :param _type_ handle: _description_
        '''
        wins = self.driver.window_handles

        current_window = self.driver.current_window_handle
        self.switch_to_window(wins[index])
        return [current_window, wins[index]]

    def switch_expand_window_tr(self, call_back, args=[], index=-1):
        '''切换到新窗口，并事务化

        :param _type_ handle: _description_
        :param _type_ call_back: _description_
        '''
        self.logger.info(f"切换到新窗口，并事务化")
        sleep(1)
        current_window = self.switch_expand_window(index)[0]
        self.logger.info(f"当前窗口句柄是 {current_window}")

        res = None

        try:
            res = call_back(*args)
        except Exception as e:
            self.logger.error(f"新窗口事务执行失败")
            self.logger.error(e)

        sleep(1)
        self.logger.info(f"关闭新窗口并切换回原来的窗口")
        self.driver.close()
        self.switch_to_window(current_window)
        return res

    def close_other_window(self, keep_window: str = None):
        '''关闭其他窗口

        :param str keep_window: 要保留的窗口, defaults to None
        '''
        keep_window = keep_window or self.driver.current_window_handle
        wins = self.driver.window_handles
        for win in wins:
            if win == keep_window:
                continue
            else:
                self.switch_to_window(win)
                self.driver.close()

        self.switch_to_window(keep_window)